//
//  Layout.m
//  CodeForConstrain
//
//  Created by 李明明 on 15/10/16.
//  Copyright © 2015年 李明明. All rights reserved.
//

#import "Layout.h"

@implementation Layout
{
    NSInteger count;
}

- (void)prepareLayout
{
    [super prepareLayout];
    count = [self.collectionView numberOfItemsInSection:0];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionViewLayoutAttributes *attri = [UICollectionViewLayoutAttributes   layoutAttributesForCellWithIndexPath:indexPath];
    CGRect rect = [UIScreen mainScreen].bounds;
    CGFloat x = arc4random() % ((int)rect.size.width - 50);
    CGFloat y = arc4random() % ((int)rect.size.height - 114);
    attri.frame = CGRectMake(x, y, 50, 50);
    return attri;
}
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *array = [@[] mutableCopy];
    for (int i = 0 ; i < count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attri = [self layoutAttributesForItemAtIndexPath:indexPath];
        for (int j = 0; j < array.count; j++) {
            UICollectionViewLayoutAttributes *att = array[j];
            if ([self isTouchFirst:att withSecnond:attri]) {
                attri = [self layoutAttributesForItemAtIndexPath:indexPath];
                j = 0;
            }
        }
        [array addObject:attri];
        NSLog(@"%d,%f,%f",i ,attri.frame.origin.x, attri.frame.origin.y);
    }
    return array;
}
- (BOOL)isTouchFirst:(UICollectionViewLayoutAttributes *)view withSecnond:(UICollectionViewLayoutAttributes *)view2
{
    CGRect rect1 = view.frame;
    CGRect rect2 = view2.frame;
    CGFloat xDistance = rect1.origin.x - rect2.origin.x;
    xDistance = xDistance > -xDistance ? xDistance : -xDistance;
    CGFloat yDistance = rect1.origin.y - rect2.origin.y;
    yDistance = yDistance > -yDistance ? yDistance : -yDistance;
    if (xDistance < rect1.size.width && yDistance < rect1.size.height) {
        return YES;
    }
    
    return NO;
}


@end
